const { Op } = require('sequelize')

const Cart = require('../model/cart.model')
const Goods = require('../model/goods.model')
const {
 findAllGoods
} = require('./goods.service')

class CartService {
 async createOrUpdate(user_id, goods_id) {
  const goods = await findAllGoods()
  const inGoods = goods.some(item => item.id == goods_id)
  if (inGoods) {
   let res = await Cart.findOne({ where: { [Op.and]: { user_id, goods_id } } })
   if (res) {
    // 已经存在的记录就把这条记录的number+1
    await res.increment('number')
    // 重新加载后返回
    return await res.reload()
   } else {
    return await Cart.create({ user_id, goods_id })
   }
  } else {
   return []
  }
 }
 async findCarts(pageNum, pageSize) {
  const offset = (pageNum - 1) * pageSize
  const limit = pageSize * 1
  const { count, rows } = await Cart.findAndCountAll({
   offset, limit,
   // 字段筛选
   attributes: ['id', 'number', 'selected'],
   // 使用联表查询
   include: {
    // 表对象
    model: Goods,
    // 字段改名为
    as: 'goods_info',
    attributes: ['id', 'goods_name', 'goods_price', 'goods_img'],
   },
  })
  return {
   pageNum, pageSize,
   total: count,
   list: rows
  }
 }
 async updateCarts(params) {
  const { id, number, selected } = params
  const res = await Cart.findByPk(id)
  if (!res) return ''
  number !== undefined ? res.number = number : ''
  if (selected !== undefined) {
   res.selected = selected
  }
  return await res.save()
 }
 async removeCarts(ids) {
  const res = await Cart.destroy({
   where: { id: { [Op.in]: ids } }
  })
  return res
 }
 async selectAllCarts(user_id) {
  const res = await Cart.update({ selected: true }, { where: { user_id } })
  return res
 }
 async unSelectAllCarts(user_id) {
  const res = await Cart.update({ selected: false }, { where: { user_id } })
  return res
 }
}

module.exports = new CartService()